package com.example.feidaolumanager.repository

import android.util.Log
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.emptyPreferences
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.map
import java.io.IOException

class UserPreferencesRepository(
    private val dataStore: DataStore<Preferences>
) {
    private companion object {
        val IS_LINEAR_LAYOUT = booleanPreferencesKey("if_show_navigation_dialog")
    }

    // 获取用户偏好设置
    val isShowNavigationDialog: Flow<Boolean> = dataStore.data.catch {
        if (it is IOException) {
            Log.e(this.toString(), "Error reading preferences.", it)
            emit(emptyPreferences())
        } else {
            throw it
        }
    }.map { preferences ->
        preferences[IS_LINEAR_LAYOUT] ?: true
    }


    /**
     * 保存用户的偏好设置
     *
     * @param isShowNavigationDialog 是否显示导航对话框
     */
    suspend fun saveLayoutPreference(isShowNavigationDialog: Boolean) {
        dataStore.edit { preferences ->
            preferences[IS_LINEAR_LAYOUT] = isShowNavigationDialog
        }
    }

}